// pages/afterPartAdd/afterPartAdd.js
const app = getApp();
import CommonService from '../../utils/service/commonService.js';
import Toast from '../../miniprogram_npm/@vant/weapp/toast/toast';
import Base64 from '../../utils/Base64.js';
const util = require('../../utils/util');

Page({

  /**
   * 页面的初始数据
   */
  data: {
    //提交按钮禁用
    disabled:false,
    //传参来的id
    id:null,
    //传参来的物流id
    logisticsId:null,
    //传参来的售后记录id
    afterssrid:null,
    //修改信息回显
    editInfo:{},
    //厂家选择框
    showFactory:false,    
    //厂家选择数据
    factoryList:[],
    //搜索厂家
    valueSearchFactory:'',
    //配件选择框
    showPart:false,
    //配件选择数据
    partList:[],
    //搜索配件
    valueSearchPart:'',
    //避免表单重复提交
    code:null,
    //是否是编辑
    isEdit:false,
    //服务详情
    serviceDetails:[],
    //费用表id
    costId:null,
    //平台id
    myAppId:null
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    this.setData({
      code:Base64.encode(new Date() + app.globalData.userInfo.userName),
      myAppId:app.globalData.myAppId
    })

    if(options.paramObj){
      let paramObj=JSON.parse(options.paramObj);

      if(paramObj.logisticsId){
        this.setData({
          logisticsId: paramObj.logisticsId
        })
      }

      if(paramObj.id){
        this.setData({
          id: paramObj.id,
          isEdit:true
        })
        //获取要修改的数据
        this.getInfo();

        //查询费用
        this.getCost();
      }

      if(paramObj.afterssrid){
        this.setData({
          afterssrid: paramObj.afterssrid
        })
        //获取售后服务详情
        this.getAfterDetail();
      }
    }
  },

  //提交表单
  confirmForm(e){
    //避免表单重复提交-先禁用按钮
    this.setData({
      disabled:true
    })

    let obj=e.detail.value;
    let td=this.data;
    let info=td.editInfo;  
    
    //无厂家
    if(td.myAppId!=7 && !info.factory){
      this.setData({
        factoryMessage: '请选择厂家',
        disabled: true
      })
      return;
    }

    //无配件
    let partName=obj.partName.trim();    
    if(!this.formNotEmpty(partName,'partMessage','请输入或选择配件')){
      return;
    } 
    
    //价格为数字
    let sealPrice=obj.sealPrice.trim();
    let num=obj.num.trim();
    let clientCosts=obj.clientCosts.trim();    

    let purchasingPrice=0;
    if(td.myAppId!=7){
      purchasingPrice=obj.purchasingPrice.trim();
      if(purchasingPrice!='' && purchasingPrice!=null){
        if(!this.formNumber(purchasingPrice,'purchasingPriceMessage','采购价格为数字')){
          return;
        }
      }
    }
    
    if(sealPrice!='' && sealPrice!=null){
      if(!this.formNumber(sealPrice,'sealPriceMessage','销售价格为数字')){
        return;
      }
    }
    if(num!='' && num!=null){
      if(!this.formNumber(num,'numMessage','数量为整数')){
        return;
      }
    }
    if(clientCosts!='' && clientCosts!=null){
      if(!this.formNumber(clientCosts,'clientCostsMessage','费用为数字')){
        return;
      }
    }

    let param={
      className:'afterSaleParts',
      data:{
        requestToken: td.code,
        id: td.id,
        //物流id
        logisticsId:td.logisticsId,
        //厂家id
        factory: info.factory,
        //厂家id
        factoryName: info.factoryName,
        //配件id
        part: info.part,
        //配件名称
        partName: partName,
        //采购价格
        purchasingPrice: Number(purchasingPrice),
        //销售价格
        sealPrice: Number(sealPrice),
        //数量
        num: parseInt(num),
        //采购总价
        totalPurchasingPrice: Number(purchasingPrice * parseInt(num)),
        //销售总价
        totalSealPrice: Number(sealPrice * parseInt(num)),
        //客户费用
        clientCosts: Number(clientCosts),
      }
    }

    //避免表单重复提交
    Toast.loading({
      duration: 0,
      forbidClick: true,
      message: '数据提交中...'
    });
    //console.log(param.data);  

    CommonService.goSave(param).then(res=>{
      if (res.statusCode == 200 && res.data.success == true){
        Toast.success('成功');

        //更新售后记录详情
        this.insertAfterDetail();

        //更新费用记录
        this.addCost(res.data.data.id,param.data);

        setTimeout(() => {
          //返回列表页并刷新数据
          this.backAndRefresh();
        }, 1000);
      }else if(res.statusCode==202){
        Toast.fail('您操作太快了,请勿重复提交');
      }else{
        Toast.fail('操作失败');
      }
    }).catch((error) => {
      Toast.fail('操作失败');
    })
  },

  //获取要修改的数据
  getInfo(){
    let param = {
      isAuth: false,
      className: 'afterSaleParts',
      data: {
        id:this.data.id,
        selectFields: ['id','logisticsId','factory','factoryName','part','partName','purchasingPrice','sealPrice','num','totalPurchasingPrice','totalSealPrice'],
        nbl:Base64.encode(util.timeFormatDay(new Date()))
      }
    }

    CommonService.goFindList(param).then(res => {
      if(res.data.data && res.data.data.result && res.data.data.result.length) {
        let result=res.data.data.result;
        console.log('配件信息回显');
        console.log(result[0]);

        this.setData({
          editInfo: result[0],
          logisticsId:result[0].logisticsId
        })
      }
    }).catch((error) => {
    })
  },

  //非空验证（field要先去掉空格）
  formNotEmpty(field,messageField,messageCon){
    if(!field){
      let obj = {};
      obj[messageField] = messageCon;
      obj['disabled'] = true;
      this.setData(obj);
      return false;
    }else{
      return true;
    }
  },

  //数字验证
  formNumber(field,messageField,messageCon){
    if(!(/^\d+(\.\d+)?$/.test(field))){
      let obj = {};
      obj[messageField] = messageCon;
      obj['disabled'] = true;
      this.setData(obj);
      return false;
    }else{
      return true;
    }  
  },

  //用户输入时清除错误提示
  clearMessage(e) {
    let field = e.target.dataset.message;
    let obj = {};
    obj[field] = "";
    obj['disabled'] = false;
    this.setData(obj);
  },

  //返回列表页并刷新数据
  backAndRefresh(){
    let pages = getCurrentPages();
    let prevPage = pages[pages.length - 2];

    prevPage.refreshListAndPage();
    wx.navigateBack();
  },

  //显示厂家选择框
  onShowFactory(){
    this.setData({
			showFactory: true
    })
    this.getFactoryList();
  },

  //查询厂家
  getFactoryList(){
    this.setData({
      factoryList: []
    })

    let param = {
      isAuth: false,
      className: 'depart',
      data: {
        searchAll: true,
        type: 2,
        selectFields: ['id', 'name']
      }
    }

    //模糊查询
    if(this.data.valueSearchFactory){
      param.data.name='%'+this.data.valueSearchFactory+'%'
    }

    CommonService.goFindList(param).then(res=>{
      if(res.data.data && res.data.data.result && res.data.data.result.length){
        let result=res.data.data.result;
        let arr=[];
        result.forEach(item => {
          arr.push({
            text:item.name,
            id:item.id
          });
        });
        this.setData({
          factoryList: arr
        })
      }
    }).catch((error) => {
    })
  },

  //隐藏厂家选择框
  onCloseFactory(){
    this.setData({
      showFactory: false,
      valueSearchFactory:''
    })
  },

  //确认厂家
  onConfirmFactory(e){
    let factory='editInfo.factory';
    let factoryName='editInfo.factoryName';
    this.setData({
      [factory]:e.detail.value.id,
      [factoryName]:e.detail.value.text,
      factoryMessage: '',
      disabled: false
    })
    this.onCloseFactory();
  },

  //搜索厂家
  onChangeFactoryVal(e){
    this.setData({
      valueSearchFactory: e.detail
    })
    this.getFactoryList();
  },

  //修改厂家
  onChangeFactory(e){
    //配件置空
    let part='editInfo.part',
        partName='editInfo.partName',
        purchasingPrice='editInfo.purchasingPrice',
        sealPrice='editInfo.sealPrice';
    this.setData({
      [part]:null,
      [partName]:'',
      [purchasingPrice]:0,
      [sealPrice]:0,
      partList:[]
    })
  },

  //显示配件选择框
  onShowPart(){
    this.setData({
			showPart: true
    })
    this.getPartList();
  },

  //查询配件
  getPartList(){
    this.setData({
      partList: []
    })

    let param = {
      isAuth: false,
      className: 'partsFactory',
      data: {
        searchAll: true,
        factory: this.data.editInfo.factory,
        selectFields: ["id","purchasingPrice","sealPrice","partsName"]
      }
    }

    //模糊查询
    if(this.data.valueSearchPart){
      param.data.partsName='%'+this.data.valueSearchPart+'%'
    }

    CommonService.goFindList(param).then(res=>{
      if(res.data.data && res.data.data.result && res.data.data.result.length){
        let result=res.data.data.result;
        let arr=[];
        result.forEach(item => {
          arr.push({
            text:item.partsName,
            id:item.id,
            obj:item
          });
        });
        this.setData({
          partList: arr
        })
      }
    }).catch((error) => {
    })
  },

  //隐藏配件选择框
  onClosePart(){
    this.setData({
      showPart: false,
      valueSearchPart:''
    })
  },

  //确认配件
  onConfirmPart(e){
    let val= e.detail.value;
    let obj=val.obj;

    let part='editInfo.part',
        partName='editInfo.partName',
        purchasingPrice='editInfo.purchasingPrice',
        sealPrice='editInfo.sealPrice';
    this.setData({
      [part]:val.id,
      [partName]:val.text,
      [purchasingPrice]:obj.purchasingPrice,
      [sealPrice]:obj.sealPrice,
      partMessage: '',
      disabled: false
    })
    this.onClosePart();
  },
  
  //搜索配件
  onChangePartVal(e){
    this.setData({
      valueSearchPart: e.detail
    })
    this.getPartList();
  },

  //获取售后服务详情
  getAfterDetail(){
    let param = {
      isAuth: false,
      className: 'afterSaleServiceRecord',
      data: {
        id:this.data.afterssrid,
        selectFields: ['id','serviceDetails']
      }
    }

    CommonService.goFindList(param).then(res => {
      if(res.data.data && res.data.data.result && res.data.data.result.length) {
        let result=res.data.data.result;
        this.setData({
          serviceDetails: result[0].serviceDetails
        })
      }
    }).catch((error) => {
    })
  },

  //更新售后记录详情
  insertAfterDetail(){
    let td=this.data;
    let user = app.globalData.userInfo;
    let serviceDetails=td.serviceDetails;

    if(td.isEdit){
      serviceDetails.push({
        content: user.userName + "修改配件信息",
        datetime: util.timeFormat(new Date())
      });
    }else{
      serviceDetails.push({
        content: user.userName + "添加配件信息",
        datetime: util.timeFormat(new Date())
      });
    }

    let param={
      className:'afterSaleServiceRecord',
      data:{
        id:td.afterssrid,
        serviceDetails:serviceDetails
      }
    }

    CommonService.goSave(param).then(res=>{
    }).catch((error) => {
    })
  },

  //查询费用
  getCost(){
    let param = {
      isAuth: false,
      className: 'afterSaleCostsRecord',
      data: {
        searchAll: true,
        itemId:this.data.id,
        type:1,
        selectFields: ['id','clientCosts'],
        nbl:Base64.encode(util.timeFormatDay(new Date()))
      }
    }
    CommonService.goFindList(param).then(res => {
      if(res.data.data && res.data.data.result && res.data.data.result.length) {
        let result=res.data.data.result;
        this.setData({
          costId: result[0].id,
          clientCosts:result[0].clientCosts.total
        })
      }
    }).catch((error) => {
    })
  },

  //添加/编辑费用记录
  addCost(id,formObj){
    let td=this.data;

    let param={
      className:'afterSaleCostsRecord',
      data:{
        id:td.costId,
        //售后记录id
        afterId:td.afterssrid,
        //类型（1配件，2上门）
        type:1,
        //配件名称
        name:formObj.partName,
        //配件表id
        itemId:id,
        //平台支付费用
        platformCosts:{
          //配件费用
          part: formObj.totalSealPrice,
          //维修费
          maintain: 0,
          //总费用
          total:formObj.totalSealPrice,
        },
        //客户支付费用
        clientCosts:{
          //配件费
          part:formObj.clientCosts,
          //服务费
          service:0,
          //总费用
          total:formObj.clientCosts,
        }
      }
    }    

    CommonService.goSave(param).then(res=>{
    }).catch((error) => {
    })
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  }
})
